package com.simoniu.first;

import java.io.*;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import javax.servlet.annotation.*;

@WebListener("onLineNumberListener")
public class OnlineNumberListener implements HttpSessionListener  {

    @Override
    public void sessionCreated(HttpSessionEvent httpSessionEvent) {

        System.out.println("session created...");
        Integer onlineNumber = 0;
        ServletContext application = httpSessionEvent.getSession().getServletContext();
        if(application.getAttribute("onlineNumber")!=null){
            onlineNumber = (Integer) application.getAttribute("onlineNumber");
        }
        onlineNumber++;
        application.setAttribute("onlineNumber",onlineNumber);

    }

    @Override
    public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
        System.out.println("session destroyed...");
        Integer onlineNumber = 0;
        ServletContext application = httpSessionEvent.getSession().getServletContext();
        if(application.getAttribute("onlineNumber")!=null){
            onlineNumber = (Integer) application.getAttribute("onlineNumber");
        }
        onlineNumber--;
        application.setAttribute("onlineNumber",onlineNumber);
    }
}